package com.cnbbx.cnbbx_web.config;

import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import java.io.IOException;

@Slf4j
@Configuration
public class DruidConfig {

    /**
     * 建议新搞个项目独立运行Druid的UI
     * 加载这个是免Druid配置的Java代码的   只需要在公共application.properties配置文件
     *         <dependency>
     *             <groupId>com.alibaba</groupId>
     *             <artifactId>druid-spring-boot-starter</artifactId>
     *             <version>1.2.17</version>
     *         </dependency>
     * Druid的UI页面需要访问就必须关闭spring-boot-starter-webflux,spring-cloud-starter-gateway
     */

    /**
     * Druid除去页面底部的广告配置
     *
     * @param properties
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean(DruidStatProperties properties) {
        log.info("====== Druid除去页面底部的广告加载完成 ======");
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                chain.doFilter(request, response);
                // 重置缓冲区，响应不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner,除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }

            @Override
            public void destroy() {
            }
        };

        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}
